package com.mrx.example.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

/**
 * 编码过滤器
 *
 * @author Mr.X
 */
@WebFilter(filterName = "编码过滤器", initParams = {@WebInitParam(name = "encoding", value = "UTF-8")}, urlPatterns = "/*")
public class EncodingFilter implements Filter {

    private String encoding;

    public void destroy() {
        encoding = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 解決请求中文乱码
        request.setCharacterEncoding(encoding);
        // 解決响应中文乱码
        // response.setCharacterEncoding("UTF-8");
        // 设置响应头
        response.setContentType("text/html; charset=" + encoding);
        // System.out.println("Do Filter");
        chain.doFilter(request, response);
    }

    public void init(FilterConfig fConfig) throws ServletException {
        encoding = fConfig.getInitParameter("encoding");
        // 处理 initParameter 为空的情况
        encoding = encoding == null || encoding.isEmpty() ? "UTF-8" : encoding;
    }

}
